import loginRTM from './rtmToken.js'
import { header, channel_text_name, channel_file_name } from './createRoom.js'
import { getWeekDate, getTime, formatDateArray, getDate } from '/js/util.js'
import loading from '/js/loading.js'
let offsetChannel = 0,
    options = {
        enableHistoricalMessaging: true,
        enableOfflineMessaging: true
    },
    client1 = null,
    channel_text = null,//文本
    channel_file = null,//文件
    start = getDate(new Date(), 7),
    teacher_img = JSON.parse(localStorage.getItem('user')).user_img,
    student_img = '',
    end = formatDateArray(new Date()),
    start_time = `${start.y}-${start.month}-${start.d}T${start.h}:${start.minute}:${start.s}Z`,
    end_time = `${end.y}-${end.month}-${end.d}T${end.h}:${end.minute}:${end.s}Z`

let createMessageWrap = async () => {
    await getStudentImg()
    $('.detail-content')[0] && $('.detail-content')[0].remove()
    let message_wrap = document.createElement('div')
    message_wrap.className = 'detail-content'
    let message_list = await getHistory()
    message_wrap.appendChild(createMessageUl(message_list))
    message_wrap.appendChild(createMessageInput())
    $(".section-course_history-detail")[0].appendChild(message_wrap);
    loginAgora()
    fileUploadListener()
    sendListener()
    imageUploadListener()
    updateContentScroll()
    scrollUlListener()
    
}

let getStudentImg = async () => {
    let res = await ajax('query_teacher_student_img',{
        studentid : window.location.href.split('/')[6].split('?')[1].split('&')[0].split('=')[1]
    },'post')
    student_img = res.data.teacherimg
}

let createMessageInput = () => {
    let message_content = document.createElement('div')
    message_content.className = 'detail-message-wrap-content'
    message_content.innerHTML = `
        <div contenteditable="true"  class='detail-message-wrap-content-input'>输入您的信息</div>
        <div>
            <i class='iconfont icon-lianjie upload-file' style='color:#919191;font-size:19px;cursor:pointer'></i>
            <i class='iconfont icon-tupian upload-img' style='margin-left:21px;color:#919191;font-size:19px;cursor:pointer'></i>
            <i class='iconfont icon-fasong send-message' style='margin-left:21px;color:#4580FE;font-size:19px;cursor:pointer'></i>
        </div>
    `
    return message_content
}

let scrollUlListener = () => {
    $('.detail-message-wrap-ul')[0].addEventListener('scroll', async (e) => {
        if (e.target.scrollTop === 0) {
            if (offsetChannel > 0) {
                if (offsetChannel > 100) {
                    offsetChannel -= 100
                }
                loading.showLoading({
                    type: 1,
                    tip: "loading..."
                })
                let res = await getMessage(channel_text_name, offsetChannel > 100 ? offsetChannel : 0)
                if (offsetChannel < 100) {
                    res = res.splice(0, offsetChannel)
                    offsetChannel = 0
                }
                appendMessageHead(res)
                loading.hideLoading();
            }
        }
    })
}

// format file size
function formatFileSize(size) {
    let value = Number(size);
    if (size && !isNaN(value)) {
        const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'];
        let index = 0;
        let k = value;
        if (value >= 1024) {
            while (k > 1024) {
                k = k / 1024;
                index++;
            }
        }
        return `${(k).toFixed(2)}${units[index]}`;
    }
    return '-';
}

//file send listener
let fileUploadListener = () => {
    $('.upload-file')[0].addEventListener('click', (e) => {
        $('.uploads-file-input')[0].addEventListener('change', async (e) => {
            if ($('.uploads-file-input')[0].files[0]) {
                let blob = $('.uploads-file-input')[0].files[0]
                let name = $('.uploads-file-input')[0].files[0].name
                //上传 Blob 对象到 Agora 服务器
                client1.createMediaMessageByUploading(blob, {
                    messageType: 'FILE',
                    fileName: name,
                    description: 'send file'
                }).then(res => {
                    const mediaMessage = res
                    channel_text.sendMessage(mediaMessage)
                    channel_text.sendMessage({
                        text: `
                        <div class='uploads-files' data-media='${mediaMessage.mediaId}'>
                            <div>${name}</div>
                            <div>${formatFileSize(mediaMessage.size)}
                        </div>`
                    }, options).then(() => {
                        createMessageSrc(`
                            <div class='uploads-files' data-media='${mediaMessage.mediaId}'>
                                <div>${name}</div>
                                <div>${formatFileSize(mediaMessage.size)}
                            </div>`, getTime(new Date()))

                        updateContentScroll()
                    }).catch(err => {
                        Dreamer.error('send fail')
                    })

                    channel_file.sendMessage({
                        text: `
                        <div class='uploads-files' data-media='${mediaMessage.mediaId}'>
                            <div>${name}</div>
                            <div>${formatFileSize(mediaMessage.size)}
                        </div>`
                    }, options)
                }).catch(err => {
                    Dreamer.error('The payload size overflow 32 MB',2000)
                 })



            }
        })
        $('.uploads-file-input')[0].click()
    })
}

//message send listener
let sendListener = () => {
    $('.send-message')[0].addEventListener('click', async () => {
        channel_text.sendMessage({ text: $('.detail-message-wrap-content-input')[0].innerHTML }, options
        ).then(() => {
            createMessageSrc($('.detail-message-wrap-content-input')[0].innerHTML, getTime(new Date()))
            updateContentScroll()
        }).catch(err => {
            Dreamer.error('send fail')
        })
    })
}

//upload image listener
let imageUploadListener = () => {
    $('.upload-img')[0].addEventListener('click', async (e) => {
        $('.uploads-img')[0].addEventListener('change', async (e) => {
            if ($('.uploads-img')[0].files[0]) {
                let { url } = await unploadimg($('.uploads-img')[0].files[0], 1024 * 1024 * 1024)
                channel_text.sendMessage(
                    { text: `<img src='${url}' width='100' height='100' />` },
                    options
                ).then(() => {
                    createMessageSrc(`<img src='${url}' width='100' height='100' />`, getTime(new Date()))
                    updateContentScroll()
                }).catch(err => {
                    Dreamer.error('send fail')
                })
            }
        })
        $('.uploads-img')[0].click()
    })
}

let updateContentScroll = () => {
    $('.detail-message-wrap-ul')[0].scrollTop = $('.detail-message-wrap-ul')[0].scrollHeight
}

let createMessageDst = (message, time) => {
    let li = document.createElement('li')
    li.className = 'chat-other'
    li.innerHTML = `
        <img width="30" height="30" style="border-radius: 50%;" src="${teacher_img}" alt="">
        <div class="chat-wrap">
            <div class="chat-content">${message}</div>	
            <div class="chat-time">${time}</div>	
        </div>
    `
    $('.detail-message-wrap-ul')[0].appendChild(li)
}

let createMessageSrc = (message, time) => {
    let li = document.createElement('li')
    li.className = 'chat-me'
    li.innerHTML = `
        <img width="30" height="30" style="border-radius: 50%;" src="${teacher_img}" alt="">
        <div class="chat-wrap">
            <div class="chat-content">${message}</div>	
            <div class="chat-time">${time}</div>	
        </div>
    `
    $('.detail-message-wrap-ul')[0].appendChild(li)
}

//create message ul wrap
let createMessageUl = (message) => {
    let message_wrap_ul = document.createElement('ul')
    message_wrap_ul.className = 'detail-message-wrap-ul'
    for (let i = 0; i < message.length; i++) {
        let li = document.createElement('li')
        li.className = `${message[i].src === JSON.parse(localStorage.getItem('user')).user_id ? 'chat-me' : 'chat-other'}`
        li.innerHTML = `
            <img width="30" height="30" style="border-radius: 50%;" src="${message[i].src === JSON.parse(localStorage.getItem('user')).user_id ? teacher_img : student_img}" alt="">
            <div class="chat-wrap">
                <div class="chat-content">${message[i].payload}</div>	
                <div class="chat-time">${getTime(message[i].ms)}</div>	
            </div>
        `
        message_wrap_ul.appendChild(li)
    }
    return message_wrap_ul
}

//append first message ul
let appendMessageHead = (message) => {
    let frag = document.createDocumentFragment()
    message.forEach(item => {
        let li = document.createElement('li')
        li.className = `${item.src === JSON.parse(localStorage.getItem('user')).user_id ? 'chat-other' : 'chat-me'}`
        li.innerHTML = `
            <img width="30" height="30" style="border-radius: 50%;" src="${message[i].src === JSON.parse(localStorage.getItem('user')).user_id ? teacher_img : student_img}" alt="">
            <div class="chat-wrap">
                <div class="chat-content">${item.payload}</div>	
                <div class="chat-time">${getTime(item.ms)}</div>	
            </div>
        `
        frag.appendChild(li)
    })
    $('.detail-message-wrap-ul')[0] && $('.detail-message-wrap-ul')[0].before(frag)
}

//search channel history
let getHistory = async () => {
    await getHistoryCount()
    let message_list = await getMessage()
    return message_list
}

//search channel history count
let getHistoryCount = async (destination = channel_text_name) => {
    let recentlyChannel = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count',
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        data: {
            destination,
            start_time,
            end_time
        },
        type: 'get'
    }).then(async res => {
        return res.count
    })
    if (recentlyChannel > 100) {
        let quotientChannel = parseInt(recentlyChannel / 100)
        offsetChannel = recentlyChannel - (quotientChannel * 100) > 0
    } else {
        offsetChannel = 0
    }
}

let getMessage = async (destination = channel_text_name, offsetChannel) => {
    let list = await $.ajax({
        url: 'https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query',
        data: JSON.stringify({
            filter: {
                destination,
                start_time,
                end_time
            },
            offset: offsetChannel,
            limit: 100
        }),
        headers: header,
        async: true, //异步或同步，默认异步
        dataType: 'json', //服务器返回类型 
        type: 'post'
    }).then(async res => {
        let { location } = res
        location = location.split('/')[5]
        let list = await $.ajax({
            url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
            type: 'get',
            headers: header,
            dataType: 'json',
            async: true
        })
        return list.messages
    }).catch(err => { console.log(err) })
    return list
}

let loginAgora = async () => {
    let { client, channel1, channel2 } = await loginRTM()
    await channel1.join().then((res) => {
        console.log(res, "You have successfully joined channel_text");
    });

    await channel2.join().then((res) => {
        console.log(res, "You have successfully joined channel_file");
    });

    channel1.on("ChannelMessage", async function (message, memberId, r) {
        if (message.messageType === 'FILE') {
            const blob = await client1.downloadMedia(message.mediaId)
            console.log('blob', blob)
            // 获得了 Blob 对象，进行其他操作
        } else {
            createMessageDst(message.text, getTime(r.serverReceivedTs))
            // console.log("message", message, "memberId", memberId,'r',r.serverReceivedTs);
            updateContentScroll()
        }
    });

    channel_text = channel1
    channel_file = channel2
    client1 = client
}


export {
    createMessageWrap
}